package com.changpei.common.exception.controller;

import com.changpei.common.result.Result;
import com.changpei.common.result.enums.CommonCode;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常捕获,包含4xx...及5xx开头异常
 *
 * @author Way on 2021/8/6
 */
@Controller
public class CommonErrorController implements ErrorController {

    /**
     * 默认返回服务器内部错误
     *
     * @param request
     * @return
     */
    @RequestMapping("/error")
    @ResponseBody
    public ResponseEntity<Result> handleError(HttpServletRequest request) {
        // 获取statusCode:401,404,500
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode.toString().startsWith("4")) {
            // 4xx异常
            return new ResponseEntity<>(Result.failed(CommonCode.DATA_NOT_FOUND), HttpStatus.valueOf(statusCode));
        }
        return new ResponseEntity<>(Result.failed(CommonCode.SERVER_INTERNAL_ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}
